package io.renren.wh.order.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.wh.common.Constant;
import io.renren.wh.merchant.entity.InfoEntity;
import io.renren.wh.merchant.entity.MerchantKeyEntity;
import io.renren.wh.merchant.service.InfoService;
import io.renren.wh.order.entity.OrderInfoEntity;
import io.renren.wh.order.enums.CallBackStatusEnum;
import io.renren.wh.order.enums.ReCallBackStatusEnum;
import io.renren.wh.order.service.OrderInfoService;
import io.renren.wh.order.util.MySignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "订单管理", tags = {"订单管理"})
@RestController
@RequestMapping("wh/orderinfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private InfoService infoService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 列表
     */
    @ApiOperation(value = "获取订单信息", notes = "获取订单信息", httpMethod = "GET")
    @RequestMapping("/list")
    @RequiresPermissions("wh:orderinfo:list")
    public R list(@ApiParam(name = "page", value = "页码", required = false)
                      @RequestParam(required = false) String page,
                  @ApiParam(name = "limit", value = "每页条数", required = false)
                      @RequestParam(required = false) String limit,
                  @ApiParam(name = "merchantname", value = "商户名称", required = false)
                      @RequestParam(required = false) String merchantname,
                  @ApiParam(name = "channelname", value = "通道名称", required = false)
                      @RequestParam(required = false) String channelname,
                  @ApiParam(name = "merchantordersn", value = "商户订单号", required = false)
                      @RequestParam(required = false) String merchantordersn,
                  @ApiParam(name = "systemordersn", value = "系统订单号", required = false)
                      @RequestParam(required = false) String systemordersn,
                  @ApiParam(name = "starttime", value = "开始日期", required = false)
                      @RequestParam(required = false) String starttime,
                  @ApiParam(name = "endtime", value = "结束日期", required = false)
                      @RequestParam(required = false) String endtime,
                  @ApiParam(name = "interfaceid", value = "支付方式(接口ID)", required = false)
                      @RequestParam(required = false) Integer interfaceid,
                  @ApiParam(name = "orderstatus", value = "订单状态：0---待充值   1---已充值   2---已失效", required = false)
                      @RequestParam(required = false) Integer orderstatus,
                  @ApiParam(name = "callbackStatus", value = "回调状态：0---未回调   1---已回调", required = false)
                      @RequestParam(required = false) Integer callbackStatus
                  ){
        Map<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("limit",limit);
        params.put("merchantname",merchantname);
        params.put("channelname",channelname);
        params.put("merchantordersn",merchantordersn);
        params.put("systemordersn",systemordersn);
        params.put("starttime",starttime);
        params.put("endtime",endtime);
        params.put("interfaceid",interfaceid);
        params.put("orderstatus",orderstatus);
        params.put("callbackStatus",callbackStatus);

        PageUtils pageUtils = orderInfoService.queryPage(params);

        return R.ok().put("page", pageUtils);
    }


    /**
     * 删除
     */
    @ApiOperation(value = "删除订单信息", notes = "删除订单信息", httpMethod = "DELETE")
    @DeleteMapping("/delete")
    @RequiresPermissions("wh:orderinfo:delete")
    public R delete(
            @ApiParam(name = "ids", value = "订单ID,比如:[1,2]", required = false)
            @RequestBody Integer[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 发起回调
     */
    @ApiOperation(value = "回调", notes = "回调", httpMethod = "GET")
    @GetMapping("/callback/{sysOrderNo}")
    public R callBack(@PathVariable("sysOrderNo") String sysOrderNo){
        if (!redisTemplate.hasKey(Constant.MERCHANT_KEY+sysOrderNo)){
            return R.error("订单不需要回调");
        }

        if (!redisTemplate.hasKey(Constant.ORDER_PREFIX+sysOrderNo)){
            return R.error("订单不需要回调");
        }
        MerchantKeyEntity merchantKey = redisUtils.fromJson(redisUtils.get(Constant.MERCHANT_KEY+sysOrderNo),MerchantKeyEntity.class);

        //如果商户状态为停用，则不做处理
        InfoEntity merchantInfo = infoService.getById(merchantKey.getMerchantid());
        if (merchantInfo == null || merchantInfo.getStatus()==1){
            return R.error("商户已停用，不需要回调");
        }

        OrderInfoEntity orderInfo = redisUtils.fromJson(redisUtils.get(Constant.ORDER_PREFIX+sysOrderNo),OrderInfoEntity.class);

        Map<String,Object> params = new HashMap<>();
        params.put("orderno",orderInfo.getMerchantordersn()); // 商户订单号
        params.put("amount",orderInfo.getOrderaccount());  //订单金额 单位 分
        params.put("paytype",orderInfo.getInterfacecode()); //订单支付方式
        params.put("sign",MySignUtil.getSign(orderInfo.getMerchantordersn(),orderInfo.getOrderaccount(),orderInfo.getInterfacecode(),merchantKey.getSecretkey()));

        String responseStr = HttpUtil.post(merchantKey.getNotifyUrl(),JSON.toJSONString(params));

        if(responseStr.equals("1")){
            orderInfo.setCallbackstatus(CallBackStatusEnum.YES.type);
            orderInfo.setRecallbackstatus(ReCallBackStatusEnum.MANUAL.type);
            orderInfo.setEndtime(new Date());
            //修改订单状态
            orderInfoService.orderCallbackSuccess(orderInfo);
            return R.ok();
        }
        return R.error("回调未成功").put("response",responseStr);
    }

}
